/*
 * importer: () => import("@/xxx/xxx.[vue,png...]")
 *  */
export async function getImporterAsync(importer) {
  return await new Promise((resolve, reject) => {
    if (typeof importer !== 'function') {
      return reject();
    }
    (async () => {
      try {
        const file = await importer();
        resolve(file ? file.default || file : undefined);
      } catch (error) {
        console.error(error);
        resolve();
      }
    })();
  });
}

/*
 * importer: () => import("@/xxx/xxx.png")
 * width: 图片 width, 可选，只会影响 img.width 的值，naturalWidth 不受影响
 * height: 图片 height, 可选，只会影响 img.height 的值，naturalHeight 不受影响
 *  */
export function getImageAsync(importer, width, height) {
  return new Promise((resolve) => {
    (async () => {
      const url = await getImporterAsync(importer);
      const img = new Image(width, height);
      img.onload = () => resolve(img);
      img.src = url;
    })();
  });
}

// 将blob转换为file
export function blobToFile(blob, fileName) {
  const type = blob.type;
  const name = fileName + '.' + type.replace(/([a-z]+\/)/, '');
  return new window.File([blob], name, { type });
}

export function fileToBlob(file, type) {
  return new Blob([file], { type: file.type || type || 'application/*' });
}
// base64转换为blob
export function base64toBlob(dataUrl) {
  const arr = dataUrl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const str = atob(arr[1]);
  let len = str.length;
  const u8arr = new Uint8Array(len);
  while (len--) {
    u8arr[len] = str.charCodeAt(len);
  }
  return new window.Blob([u8arr], { type: mime });
}

export function base64toFile(dataUrl, fileName) {
  return blobToFile(base64toBlob(dataUrl), fileName);
}

export function saveFile(url, name) {
  const a = document.createElement('a');
  a.download = name;
  a.href = url;
  a.click();
}

export async function saveBlobFile(blob, name, format) {
  if (format) {
    try {
      let buffer = await blob.arrayBuffer();
      blob = new Blob([buffer], format);
    } catch (error) {
      console.log(error);
    }
  }
  const url = window.URL.createObjectURL(blob);
  saveFile(url, name);
  window.URL.revokeObjectURL(url);
}

export async function download(url, name, format) {
  if (url instanceof Blob) {
    return await saveBlobFile(url, name, format);
  }
  if (typeof url === 'string') {
    const xhr = new window.XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onerror = () => {
      window.open(url, name);
    };
    xhr.onload = async () => {
      await saveBlobFile(xhr.response, name, format);
    };
    xhr.send();
  }
}
